package com.xiaohei.rabbitmq.three;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.xiaohei.rabbitmq.utils.RabbitmqUtils;
import com.xiaohei.rabbitmq.utils.SleepUtils;

import java.nio.charset.StandardCharsets;

/**
 * @Description: 消费在手动应答时不丢失，放回队列中重新消费
 * @Author: 王希辰
 * @Date: 2022/3/17 18:27
 */
public class Worker03 {
    //队列名称
    public static final String TASK_QUEUE_NAME="ack_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitmqUtils.getChannel();
        System.out.println("c1等待接收消息处理时间较短");
        DeliverCallback deliverCallback=(consumerTag, message) -> {
            //沉睡1S
            SleepUtils.sleep(1);
            System.out.println("接收到消息"+new String(message.getBody(), StandardCharsets.UTF_8));
            //手动应答
            //1.消息标记
            //2.是否批量
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };
        //设置不公平分发
        //不公平分发
        //int prefetchCount=1;
        //预取值
        int prefetchCount=2;
        channel.basicQos(prefetchCount);
        //采用手动应答
        boolean autoAck=false;
        channel.basicConsume(TASK_QUEUE_NAME,autoAck,deliverCallback,(consumerTag -> {
            System.out.println(consumerTag+"消费者取消消费接口回调逻辑");
        }));
    }

}
